//
//  TJRefreshControl.swift
//  WeiBo
//
//  Created by TanJian on 15/12/12.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit

let RefreshControlH : CGFloat = 50

enum TJRefreshControlState: Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class TJRefreshControl: UIControl {

    // MARK: - 懒加载控件
    // 简单
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 显示文字的label
    private lazy var noticeLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    // 菊花转
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    // 其被添加到的父控件(可以滚动)
    var scrollView: UIScrollView?
    
    var oldState:TJRefreshControlState = .Normal
    
    var newState: TJRefreshControlState = .Normal{
        didSet{
            
            switch newState{
            case .Pulling:
                noticeLabel.text = "松开刷新"
                arrowIcon.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                noticeLabel.text = "正在刷新"
                arrowIcon.hidden = true
                indicator.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top += RefreshControlH
                    self.scrollView?.contentInset = contentInset
                })
                
                sendActionsForControlEvents(.ValueChanged)
            case .Normal:
                noticeLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicator.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                //从刷新状态到默认状态时执行
                if oldState == .Refreshing{
                    //顶部停留距离
                    UIView.animateWithDuration(1, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= RefreshControlH
                        self.scrollView?.contentInset = contentInset
                    
                    })
                    
                }
                
            }
            oldState = newState
        }
        
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefresh(){
        newState = .Normal
    }
    
    private func setupUI(){
        backgroundColor = UIColor.redColor()
        
        var frame = self.frame
        frame.size = CGSizeMake(TJScreen.width, RefreshControlH)
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        // 添加控件
        addSubview(arrowIcon)
        addSubview(noticeLabel)
        addSubview(indicator)
        
        // 添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        noticeLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    //当前控件要添加到另一个控件上时调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let scrollView = newSuperview as? UIScrollView{
            
            //kvo监听newSuperview的content滚动
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            
            self.scrollView = scrollView
            
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            self.frame = frame
        }
    }
    

    //监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = scrollView?.contentOffset.y
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        //上部状态变换的临界值
        let criticalValue = -contentInsetTop-RefreshControlH
        
        if scrollView!.dragging{
            //默认状态
            if newState == .Normal && contentOffsetY < criticalValue{
                newState = .Pulling
            }else if newState == .Pulling && contentOffsetY >= criticalValue{
                newState = .Normal
            }
        }else{
            if newState == .Pulling{
                newState = .Refreshing
            }
        }
    }
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}








